#!/bin/sh
set -e
set -x

[ ! -d /root/.ethereum/geth/chaindata ] && geth init /config/genesis.json
[ $RPC ] && RPCOPT="--authrpc.vhosts=* --authrpc.addr=0.0.0.0 --authrpc.port=8551"
[ $WS ] && WSOPT="--ws --ws.addr=0.0.0.0 --ws.port=8546 --ws.origins=* --ws.api=eth,txpool,debug,web3,net,personal,admin,miner"
[ $HTTP ] && HTTPOPT="--http --http.addr=0.0.0.0 --http.corsdomain=* --http.port=8545 --http.api=eth,txpool,debug,web3,net,personal,engine,admin,miner"
[ $SINGER ] && MINE="--mine --miner.threads=1 --miner.gasprice=1000000000 --miner.etherbase=0x$ACCOUNT --unlock=0x$ACCOUNT --password=/config/password"
[ $NETWORKID ] && NETWORK="--networkid=$NETWORKID"
ENODE=`bootnode --nodekey=/bootnode_keys/boot.key -writeaddress`
while true
do
  BOOTNODEIP=`ping -c 1 bootnode|awk -F '[()]' 'NR==1{print $2}'`
  if [ ! -z $BOOTNODEIP ];then
    break
  fi
done
ipnum=0
ip2num() {
  local ip=$1
  local a=$(echo $ip | awk -F '.' '{print $1}')
  local b=$(echo $ip | awk -F '.' '{print $2}')
  local c=$(echo $ip | awk -F '.' '{print $3}')
  local d=$(echo $ip | awk -F '.' '{print $4}')
  #echo "$(( (a<<24)+(b<<16)+(c<<8)+d ))"
  ipnum="$(( (a<<24)+(b<<16)+(c<<8)+d ))"
  echo ${ipnum}
}
ip2num $BOOTNODEIP
newipnum=`expr ${ipnum} + 1`

newip=0
num2ip() {
  local num=$1
  local a=$((num>>24))
  local b=$((num>>16&0xff))
  local c=$((num>>8&0xff))
  local d=$((num&0xff))
  newip="$a.$b.$c.$d"
}
num2ip $newipnum
echo "----------------> bootnodeip is: ${BOOTNODEIP} ------------------------>"
BOOTNODE="--bootnodes enode://$ENODE@[$newip]:30301"

KEYSTORE=/root/.ethereum/keystore
cp /config/keystore/* $KEYSTORE

geth \
    $RPCOPT \
    $WSOPT \
    $HTTPOPT \
    $MINE \
    $NETWORK \
    $BOOTNODE \
    --allow-insecure-unlock \
    --port=30301 \
    --nodiscover \
    --verbosity $LOGGING_LEVEL
